package com.object.oriented.exam.system5.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.object.oriented.exam.system5.entity.Exam;
import com.object.oriented.exam.system5.entity.Score;
import com.object.oriented.exam.system5.mapper.ExamMapper;
import com.object.oriented.exam.system5.mapper.ScoreMapper;
import com.object.oriented.exam.system5.service.ExamService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author xdf
 * @date 2023-06-14
 */
@Service
public class ExamServiceImpl implements ExamService {

  @Resource ExamMapper examMapper;

  @Resource ScoreMapper scoreMapper;

  @Override
  public Boolean addExam(Exam exam) {
    return examMapper.insert(exam) > 0;
  }

  @Override
  public Boolean attendExam(Score score) {
    Exam exam = examMapper.selectById(score.getExamId());
    if (exam != null) {
      QueryWrapper<Score> scoreQueryWrapper=new QueryWrapper<>();
      scoreQueryWrapper
              .eq("student_id",score.getStudentId())
              .eq("exam_id",score.getExamId())
              ;
      Score pre=scoreMapper.selectOne(scoreQueryWrapper);
      if(pre!=null){
        return true;
      }
      return scoreMapper.insert(score)>0;
    }
    return false;
  }

  @Override
  public Exam getExam(Long id) {
    return examMapper.selectById(id);
  }

  @Override
  public Page<Exam> getExamInPage(Long current, Long size,Long studentId) {
    Page<Exam> examPage = new Page<>(current, size);
    examMapper.selectPage(examPage, null);
    if (studentId!=0){
      for(Exam exam:examPage.getRecords()){
        QueryWrapper<Score> scoreQueryWrapper=new QueryWrapper<>();
        scoreQueryWrapper
                .eq("student_id",studentId)
                .eq("exam_id",exam.getId())
        ;
        Score score=scoreMapper.selectOne(scoreQueryWrapper);
        if(score!=null){
          exam.setStatus((byte) 1);
        }
      }
    }
    return examPage;
  }
}
